package com.random.fox.whatspay.ui;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.Keyframe;
import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gc.materialdesign.widgets.ColorSelector;
import com.random.fox.whatspay.AppContext;
import com.random.fox.whatspay.R;
import com.random.fox.whatspay.bean.Cost;
import com.random.fox.whatspay.greendao.dao.CostDao;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * 显示详细的花费信息
 * Created by 渠 on 2014/11/8.
 */
public class DetailFragment extends BaseFragment {
    private AppContext appContext;
    private CostDao costDao;
    private RecyclerView recyclerView;
    private List<Cost> costs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        host = inflater.inflate(R.layout.detail_fragment,null);
        return host;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        appContext = (AppContext) mainAty.getApplicationContext();
        costDao = appContext.getCostDao();
        initView();
        initData();
    }

    @Override
    void initView() {
        recyclerView = (RecyclerView) findViewById(R.id.bill_list);

        initData();
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mainAty);
        recyclerView.setLayoutManager(mLayoutManager);
        MyAdapter adapter = new MyAdapter(costs);
        recyclerView.setAdapter(adapter);


        findViewById(R.id.toBill).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(view.getContext(),BillAty.class));
            }
        });
    }

    @Override
    void initData() {
        QueryBuilder<Cost> costQueryBuilder = costDao.queryBuilder();
        Long accountId = appContext.getCurrentAccount().getId();
        costQueryBuilder.where(CostDao.Properties.AccountId.eq(accountId));
        costs = costQueryBuilder.list();
    }

    LayoutTransition mTransitioner;
    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
        private List<Cost> costs;

        public class ViewHolder extends RecyclerView.ViewHolder {
            //根布局
            RelativeLayout root;
            //
            public RelativeLayout dayContainer;
            //右侧的card
            public CardView cardView;
            //消费的金额
            public TextView mCost;
            //备注信息（默认是隐藏的）
            public TextView mark;
            //隐藏块,包含时间，备注等信息
            public View hide;
            //这个月的几号
            public TextView dayInMonth;
            //这个星期的星期几
            public TextView dayInWeek;
            //day的分界线
            public ImageView divider;
            public ViewHolder(RelativeLayout v) {
                super(v);
                root = v;
            }
        }

        // Provide a suitable constructor (depends on the kind of dataset)
        public MyAdapter(List<Cost> costs) {
            this.costs = costs;
        }

        // Create new views (invoked by the layout manager)
        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                       int viewType) {
            View root = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.my_text_view, parent, false);


            final ViewHolder vh = new ViewHolder((RelativeLayout)root);
            vh.cardView = (CardView) root.findViewById(R.id.card);
            vh.mCost = (TextView) root.findViewById(R.id.cost);
            vh.mark = (TextView) root.findViewById(R.id.tv_remark);
            vh.hide = root.findViewById(R.id.hide);
            vh.dayContainer = (RelativeLayout) root.findViewById(R.id.rl_day_container);
            vh.dayInMonth = (TextView) root.findViewById(R.id.tv_day_in_month);
            vh.dayInWeek = (TextView) root.findViewById(R.id.tv_day_in_week);
            vh.divider = (ImageView) root.findViewById(R.id.im_date_divider);

            mTransitioner = new LayoutTransition();
            vh.cardView.setLayoutTransition(mTransitioner);
            vh.cardView.setMaxCardElevation(5);
            vh.cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (vh.hide.getVisibility() == View.VISIBLE) {
                        vh.hide.setVisibility(View.GONE);
                    } else {
                        vh.hide.setVisibility(View.VISIBLE);
                    }
                }
            });

            vh.cardView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    final ColorSelector colorSelector = new ColorSelector(view.getContext(), Color.RED, null);
                    colorSelector.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialogInterface) {
                            changeColor(vh.cardView,colorSelector.getColor());
                        }
                    });
                    colorSelector.show();
                    return true;
                }
            });

            setupCustomAnimations();
            return vh;
        }

        //CardView 背景修改代码
        private void changeColor(CardView cardView,int color) {
            try {
                Class clz = Class.forName("android.support.v7.widget.RoundRectDrawableWithShadow");
                Constructor[] constructors = clz.getDeclaredConstructors();
                Constructor constructor = constructors[0];
                constructor.setAccessible(true);
                Object o = constructor.newInstance(cardView.getResources(),color, cardView.getRadius()
                        , 0, cardView.getMaxCardElevation());
                cardView.setBackgroundDrawable((android.graphics.drawable.Drawable) o);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (java.lang.InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {

            //    holder.cardView.setRadius(position);
            final Cost cost = costs.get(position);
            holder.mCost.setText(cost.getCost()+"￥");
            //设置备注
            holder.mark.setText("\t\t"+cost.getDes()+"");

            if (position == 4){
                holder.divider.setVisibility(View.VISIBLE);
            }else{
                holder.divider.setVisibility(View.GONE);
            }

            Date date = cost.getDate();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int day = calendar.get(Calendar.DAY_OF_WEEK);

        }

        @Override
        public int getItemCount() {
            return costs.size();
        }
    }

    // 生成自定义动画
    private void setupCustomAnimations() {
        // 动画：CHANGE_APPEARING
        // Changing while Adding
        PropertyValuesHolder pvhLeft = PropertyValuesHolder.ofInt("left", 0, 1);
        PropertyValuesHolder pvhTop = PropertyValuesHolder.ofInt("top", 0, 1);
        PropertyValuesHolder pvhRight = PropertyValuesHolder.ofInt("right", 0,
                1);
        PropertyValuesHolder pvhBottom = PropertyValuesHolder.ofInt("bottom",
                0, 1);
        PropertyValuesHolder pvhScaleX = PropertyValuesHolder.ofFloat("scaleX",
                1f, 0f, 1f);
        PropertyValuesHolder pvhScaleY = PropertyValuesHolder.ofFloat("scaleY",
                1f, 0f, 1f);

        final ObjectAnimator changeIn = ObjectAnimator.ofPropertyValuesHolder(
                this, pvhLeft, pvhTop, pvhRight, pvhBottom, pvhScaleX,
                pvhScaleY).setDuration(
                mTransitioner.getDuration(LayoutTransition.CHANGE_APPEARING));
        mTransitioner.setAnimator(LayoutTransition.CHANGE_APPEARING, changeIn);
        changeIn.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setScaleX(1f);
                view.setScaleY(1f);
            }
        });

        // 动画：CHANGE_DISAPPEARING
        // Changing while Removing
        Keyframe kf0 = Keyframe.ofFloat(0f, 0f);
        Keyframe kf1 = Keyframe.ofFloat(.9999f, 360f);
        Keyframe kf2 = Keyframe.ofFloat(1f, 0f);
        PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe(
                "rotation", kf0, kf1, kf2);
        final ObjectAnimator changeOut = ObjectAnimator
                .ofPropertyValuesHolder(this, pvhLeft, pvhTop, pvhRight,
                        pvhBottom, pvhRotation)
                .setDuration(
                        mTransitioner
                                .getDuration(LayoutTransition.CHANGE_DISAPPEARING));
        mTransitioner.setAnimator(LayoutTransition.CHANGE_DISAPPEARING,
                changeOut);
        changeOut.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotation(0f);
            }
        });

        // 动画：APPEARING
        // Adding
        ObjectAnimator animIn = ObjectAnimator.ofFloat(null, "rotationY", 90f,
                0f).setDuration(
                mTransitioner.getDuration(LayoutTransition.APPEARING));
        mTransitioner.setAnimator(LayoutTransition.APPEARING, animIn);
        animIn.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotationY(0f);
            }
        });

        // 动画：DISAPPEARING
        // Removing
        ObjectAnimator animOut = ObjectAnimator.ofFloat(null, "rotationX", 0f,
                90f).setDuration(
                mTransitioner.getDuration(LayoutTransition.DISAPPEARING));
        mTransitioner.setAnimator(LayoutTransition.DISAPPEARING, animOut);
        animOut.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotationX(0f);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (recyclerView != null){
            initData();
//            recyclerView.getAdapter().notifyDataSetChanged();
            recyclerView.setAdapter(new MyAdapter(costs));
        }
    }
}
